# -*- coding: utf-8 -*-
from typing import Optional, Awaitable

from tornado import web, ioloop
from json import loads

class IndexHandler(web.RequestHandler):
    # 初始化Handler
    def initialize(self, db = None):
        self.db = db

    # 准备Handler，一般是日志，打开文件
    def prepare(self):
        print("111")

    # 结束Handler，一般是清理内容
    def on_finish(self):
        print("333")

    async def get(self):
        print("222")
        name = self.get_query_argument('q')
        names = self.get_query_arguments('q')
        print(f"Name: {name}")
        print(f"Names: {names}")
        self.write(f'Hello, world!')

    async def post(self):
        name = self.get_body_argument('q')
        names = self.get_body_arguments('q')
        name = self.get_argument('q')
        names = self.get_arguments('q')
        args = self.request.body.decode('utf-8')
        print(loads(args))
        print(name)
        print(names)
        self.write('成功访问post请求！')
        self.finish('msg', '成功访问')

class UserHandler(web.RequestHandler):
    async def get(self, id):
        self.write(f'Hello, your id is {id}!')

class UserNameHandler(web.RequestHandler):
    async def get(self, name):
        self.write(f'Hello, your name is {name}!')

class UserNamePasswordHandler(web.RequestHandler):
    async def get(self, name, password):
        self.write(f'Hello, your name is {name} and your password is {password}!')

class RedirectHandler(web.RequestHandler):
    def initialize(self, name, password):
        self.name = name
        self.password = password
        print(f"Name is {name}, password is {password}")

    async def get(self):
        self.redirect(self.reverse_url('index'))

args = {
    "name": "lace",
    "password": "ronaldqinbiao"
}

if __name__ == '__main__':
    app = web.Application([
        web.URLSpec('/', IndexHandler, name='index'),
        (r'/user/(\d+)/?', UserHandler),
        (r'/user/(\w+)/?', UserNameHandler),
        # (r'/user/(\w+)/(\w+)/?', UserNamePasswordHandler),
        (r'/user/(?P<name>\w+)/(?P<password>\w+)/?', UserNamePasswordHandler),
        web.URLSpec('/redirect/?', RedirectHandler, args),
    ], debug=True)
    app.listen(8000)
    ioloop.IOLoop.current().start()